package com.zenchn.aliyun.oss.api.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.zenchn.aliyun.oss.api.OssDeleteService;
import com.zenchn.aliyun.oss.utils.OssCommonUtils;
import com.zenchn.entity.JsonResult;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * oss删除 实现类
 * @author dingxinfa
 * @date 2018-08-16
 *
 */
@Service
public class OssDeleteServiceImpl implements OssDeleteService {

	
	/**
	 * 删除单个文件
	 */
	@Override
	public JsonResult<Object> deleteFile(String endpoint, String accessKeyId, String accessKeySecret, String bucketName, String objectName) {
		JsonResult jsonResult=new JsonResult();
		jsonResult.setSuccess(false);
		jsonResult.setCode(0);

		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
		try{
			// 判断文件是否存在。
			boolean found = ossClient.doesObjectExist(bucketName, objectName);
			if(found){
				// 删除文件。
				ossClient.deleteObject(bucketName, objectName);
			}

			jsonResult.setSuccess(true);
			jsonResult.setCode(1);
			// 关闭OSSClient。
			ossClient.shutdown();
		} catch (OSSException oe) {
			jsonResult.setData(OssCommonUtils.extractOSSException(oe));
		} catch (ClientException ce) {
			jsonResult.setData(OssCommonUtils.extractClientException(ce));
		} finally {
			//关闭客服端释放资源
			if (ossClient != null) {
				ossClient.shutdown();
			}
		}

		return jsonResult;

	}
	
	/**
	 * 删除多个文件
	 */
	@Override
	public JsonResult<Object> deleteFileList(String endpoint, String accessKeyId, String accessKeySecret, String bucketName, List<String> objectNameList) {


		JsonResult jsonResult=new JsonResult();
		jsonResult.setSuccess(false);
		jsonResult.setCode(0);

		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
		try{

			DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(objectNameList).withQuiet(true));
			List<String> deleteFailureList = deleteObjectsResult.getDeletedObjects();

			if (null==deleteFailureList || deleteFailureList.isEmpty()){
				jsonResult.setSuccess(true);
				jsonResult.setCode(1);
			}else if (deleteFailureList.size()>0 && deleteFailureList.size()<objectNameList.size()){
				jsonResult.setSuccess(true);
				jsonResult.setCode(1);
				jsonResult.setMessage("部分对象删除失败，详情见data");
				jsonResult.setData(deleteFailureList);
			}
			// 关闭OSSClient。
			ossClient.shutdown();
		} catch (OSSException oe) {
			jsonResult.setData(OssCommonUtils.extractOSSException(oe));
		} catch (ClientException ce) {
			jsonResult.setData(OssCommonUtils.extractClientException(ce));
		} finally {
			//关闭客服端释放资源
			if (ossClient != null) {
				ossClient.shutdown();
			}
		}
		return jsonResult;
	}

	
}
